package com.app.asktom;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.NavUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.app.asktom.abs.AbsActivity;
import com.app.asktom.abs.AbsHttpAsync;
import com.app.asktom.component.Config;
import com.app.asktom.component.DeviceHelper;
import com.app.asktom.component.HttpMultipartHelper;
import com.app.asktom.model.User;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.model.LatLng;
//import com.rdc.GetCurrentLocation.MyLocationListener;

public class UploadActivity extends AbsActivity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener{ 

	private static int RESULT_LOAD_IMAGE = 1;
	private static String coordinates;
	private String provider;
	private String sourceFileDir;
	Builder picNameBuilder;
	protected UploadActivity uploadActivity;
	private EditText picName;
	private UploadTask uploadTask;
	private LocationManager lManager;
	private LocationManager locationMangaer=null;
	private MyLocationListener locationListener=null;	
	private Boolean flag = false;
	
    private final static int
    CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private LocationClient mLocationClient;
    private Location mCurrentLocation;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload);
		this.turnGPSOn();
		mLocationClient = new LocationClient(this, this, this);
	}
	
	/*----------Method to create an AlertBox ------------- */
	protected void alertbox(String title, String mymessage) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mymessage)
				.setCancelable(false)
				.setTitle(title)
				.setPositiveButton("Set",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// finish the current activity
								// AlertBoxAdvance.this.finish();
								DeviceHelper.setGPS(true);
								dialog.cancel();
								dialog.dismiss();
								Intent myIntent = new Intent(
										Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								startActivity(myIntent);
								
							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// cancel the dialog box
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public void showMap(View view) {
		Intent intent = new Intent(this,MapCoordinateActivity.class);
		startActivity(intent);
	}
	
	public void turnGPSOn()
	{
	     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
	     intent.putExtra("enabled", true);
	     this.sendBroadcast(intent);

	    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
	    if(!provider.contains("gps")){ //if gps is disabled
	        final Intent poke = new Intent();
	        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
	        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
	        poke.setData(Uri.parse("3")); 
	        this.sendBroadcast(poke);


	    }
	}
	
	/*----------Listener class to get coordinates ------------- */
	public class MyLocationListener implements LocationListener {
		private UploadActivity uploadActivity;
		
		public void setUploadActivity(UploadActivity activity) {
			this.uploadActivity = activity;
		}
		
        @Override
        public void onLocationChanged(Location loc) {
          
//            	editLocation.setText("");
//            	pb.setVisibility(View.INVISIBLE);
                Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
                                + " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
                String longitude = "Longitude: " +loc.getLongitude();  
//    			Log.v(TAG, longitude);
    		    String latitude = "Latitude: " +loc.getLatitude();
//    		    Log.v(TAG, latitude);
    		    
    		    /*----------to get City-Name from coordinates ------------- */
    		    String cityName=null;      		      
    		    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());      		     
    		    List<Address>  addresses;  
    		    try {  
    		     addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
    		     if (addresses.size() > 0)  
    		      System.out.println(addresses.get(0).getLocality());  
    		     cityName=addresses.get(0).getLocality();  
    		    } catch (IOException e) {    		      
    		     e.printStackTrace();  
    		    } 
    		    
    		    String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
    		    Toast.makeText(this.uploadActivity, s, Toast.LENGTH_LONG).show();
//     		    editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub        	
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub        	
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub        	
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_upload, menu);
		return true;
	}

	
	public void selectPhoto(View view) {
//		this.turnGPSOn();
//	    LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);         
//

	    
		
		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media
				.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, RESULT_LOAD_IMAGE);
		
//	    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
//	    Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//
//	    double latitude=0;
//	    double longitude=0;
//	    latitude = location.getLatitude();
//	    longitude = location.getLongitude();
//	    
//	    Toast.makeText(this, "lat: " + latitude + " long: " + longitude, Toast.LENGTH_LONG);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == RESULT_LOAD_IMAGE && 
				resultCode == RESULT_OK && null != data) {
			Log.d("DEBUG", data.getData() + "==== uri");
			Uri selectedImage = data.getData();
			String[] filePathColumn = {MediaStore.Images.Media.DATA};
			Cursor cursor = getContentResolver().query(selectedImage,
				filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			ImageView imageView = (ImageView) 
					findViewById(R.id.imgUpload);
//			Bitmap selectedBitmap = BitmapFactory.decodeFile(picturePath);
			
//			imageView.setImageBitmap();
			Log.d("UPSTAT", picturePath);
			this.sourceFileDir = picturePath;
			Bitmap image = Bitmap.createBitmap(BitmapFactory.decodeFile(picturePath));
			/*ByteArrayOutputStream blob = new ByteArrayOutputStream();
			resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);*/
			
			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
			int width = metrics.widthPixels;
			int height = metrics.heightPixels;
			
			imageView.setImageBitmap(image);
			imageView.setMaxWidth(width);
			try {
				ExifInterface exif = new ExifInterface(picturePath);
				Toast t = Toast.makeText(getApplicationContext(), getTagString(ExifInterface.TAG_GPS_LATITUDE, DeviceHelper.getLatitude()) + " " + getTagString(ExifInterface.TAG_GPS_LONGITUDE, DeviceHelper.getLongtitude()), Toast.LENGTH_LONG);
//				Toast t = Toast.makeText(getApplicationContext(), getTagString(ExifInterface.TAG_GPS_LATITUDE, exif) + " " + getTagString(ExifInterface.TAG_GPS_LONGITUDE, exif), Toast.LENGTH_LONG);
				t.show();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private String getTagString(String tag, ExifInterface exif) {
		// TODO Auto-generated method stub
		 return(tag + " : " + exif.getAttribute(tag) + "\n");
	}
	
	private String getTagString(String tag, String msg) {
		return(tag + " : " + msg + "\n");
	}

	public void uploadFile(View view){
		if(this.sourceFileDir != null){
			picName = new EditText(this);
			picNameBuilder = new AlertDialog.Builder(this);
			picNameBuilder.setTitle("Picture name:");
			picNameBuilder.setView(picName);
			picNameBuilder.setCancelable(false);
			uploadActivity = this;
			picNameBuilder.setPositiveButton("Upload", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					uploadActivity.uploadTask = new UploadTask();
					uploadActivity.uploadTask.setShowLoading(true);
					uploadActivity.uploadTask.setActivity(uploadActivity);
					uploadActivity.uploadTask.execute(Config.getInstance().get("baseUrl"), uploadActivity.sourceFileDir, uploadActivity.picName.getText().toString());
				}
			});
			
			picNameBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			picNameBuilder.show();
			
		} else {
			
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class UploadTask extends AbsHttpAsync {
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			Log.d("UPSTAT", result);
			Intent viewFood = new Intent(getApplicationContext(), ViewFoodActivity.class);
			viewFood.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(viewFood);
			super.onPostExecute(result);
		}
		
		@Override
		protected String doInBackground(String... params) {
			User user = new User(this.activity);
			Map<String, String> map = user.getUserInfo();			
//			UploadActivity.coordinates = "12.12345678,14.9876543";
			
			UploadActivity.coordinates = DeviceHelper.getLatitude() + "," + DeviceHelper.getLongtitude();
			DeviceHelper.resetCoordinate();
			Log.d("DEBUG", UploadActivity.coordinates + "=================================");
			HttpMultipartHelper httpMultiHelper = new HttpMultipartHelper();
			httpMultiHelper.setUploadUrl(params[0]);
			httpMultiHelper.setSourceFileDir(params[1]);
			httpMultiHelper.addToMap("appId", "WBTOM");
			httpMultiHelper.addToMap("req", "PUT");
			httpMultiHelper.addToMap("user", map.get("phoneNumber"));
			httpMultiHelper.addToMap("pass", map.get("password"));
			httpMultiHelper.addToMap("coord", UploadActivity.coordinates);
			httpMultiHelper.addToMap("add", "");
			httpMultiHelper.addToMap("categ", "FOOD");
			httpMultiHelper.addToMap("establishment", "");
			httpMultiHelper.addToMap("name", params[2]);
			httpMultiHelper.addToMap("tags", "");
			httpMultiHelper.addToMap("meter", "SPOONS:1");
			httpMultiHelper.sendRequest();
			Log.i("UPSTAT", map.get("phoneNumber")+" "+map.get("password")+" "+UploadActivity.coordinates);
			return httpMultiHelper.getResponse();
		}
	}

	@Override
	public void onConnected(Bundle arg0) {
		mCurrentLocation = mLocationClient.getLastLocation();

		try {
			if(DeviceHelper.getLongtitude().equals(""))
				DeviceHelper.storeCoordinates(mCurrentLocation.getLongitude(), mCurrentLocation.getLatitude());
//			Toast.makeText(this, String.valueOf(mCurrentLocation.getLatitude()) + "," + String.valueOf(mCurrentLocation.getLongitude()) , Toast.LENGTH_LONG).show();
		} catch(Exception e) {
//			Toast.makeText(this, "Please enable google service", Toast.LENGTH_SHORT).show();
			if(DeviceHelper.isSetGPS() == false)
				alertbox("Google's Location Service", "Please enable your google service");
		}

	}

	@Override
	public void onDisconnected() {
        Toast.makeText(this, "Disconnected. Please re-connect.",
                Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(
                        this,
                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
//            showErrorDialog(connectionResult.getErrorCode());
        }
		
	}

    @Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mLocationClient.connect();
    }
    
    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        mLocationClient.disconnect();
        super.onStop();
    }
    
}
